package com.cs.service;

import com.cs.mapper.DrugpeopleMapper;
import com.cs.pojo.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Sans
 */
@Service
public class DrugPeopleService {
    
    @Resource
    private DrugpeopleMapper drugpeopleMapper;
    
    @Resource
    private DrugService drugService;
    @Resource
    private PeopleService peopleService;
    
    
    /**
     * 指定id查询 drId 或 peopleId
     *      bool(true): erId
     *      bool(false): peopleId
     * @param id
     * @param bool
     * @return
     */
    @Transactional (propagation = Propagation.REQUIRES_NEW , readOnly = true)
    public List<Drugpeople> queryByType(int id , boolean bool) {
        DrugpeopleExample example = new DrugpeopleExample();
        DrugpeopleExample.Criteria criteria = example.createCriteria();
        if (bool){
            criteria.andDrIdEqualTo(id);
        }else{
            criteria.andBehIdEqualTo(id);
        }
        return drugpeopleMapper.selectByExample(example);
    }
    
    /**
     * 列表查询
     */
    @Transactional (propagation = Propagation.REQUIRES_NEW , readOnly = true)
    public PageInfo<Drugpeople> queryByPage(Integer pageNum, Integer pageSize,int peopleId) {
        
        DrugpeopleExample example = new DrugpeopleExample();
        DrugpeopleExample.Criteria criteria = example.createCriteria();
        
        if (peopleId > 0) {
            criteria.andBehIdEqualTo(peopleId);
        }
        
        List<Drugpeople> list = drugpeopleMapper.selectByExample(example);
        PageHelper.startPage(pageNum,pageSize);
        List<Drugpeople> newList = new ArrayList<>();
        //填充数据 （实现多表查询结果）
        for (Drugpeople d : list) {
            Drug drug = drugService.queryById(d.getDrId());
            d.setDrName(drug.getDrName());
            People people = peopleService.queryById(d.getBehId());
            d.setBehName(people.getBehName());
            d.setBehNursepeople(people.getBehNursepeople());
            newList.add(d);
        }
        return new PageInfo<>(newList);
    }
    
    @Transactional (propagation = Propagation.REQUIRED ,rollbackFor = {Exception.class})
    public int add(Drugpeople drugpeople){
        return drugpeopleMapper.insertSelective(drugpeople);
    }
    
    /**
     * 更新数据
     * @return
     */
    @Transactional (propagation = Propagation.REQUIRED ,rollbackFor = {Exception.class})
    public int update(Drugpeople drugpeople){
        return drugpeopleMapper.updateByPrimaryKeySelective(drugpeople);
    }
    
    
    
    
}
